import sys
from pyparsing import (Combine, Group, Literal, OneOrMore, Optional, Suppress,
                       Word, ZeroOrMore, alphanums, alphas, alphas8bit, nums)


class pyparsing_onetab():

    def genpattern(self):
        unicodePrintables = ''.join(
            chr(c) for c in range(sys.maxunicode) if not chr(c).isspace())
        word = Word(alphas + alphanums + "/:!.-_?&=-+#%")
        titleword = Word(alphas + alphanums + "/:!. " + unicodePrintables)
        urlfield = Group(OneOrMore(word)).set_results_name("url")
        titlefield = Group(OneOrMore(titleword)).set_results_name("title")

        # 在输出时，不需要针对它的输出结果
        splitflag = Suppress(Literal('|'))
        onetabpattern = urlfield + splitflag + titlefield
        return onetabpattern

    def parseOnetab(self, onetabfilename, resultfilename):
        pattern = self.genpattern()

        def markdown(inputstr) -> str:
            # url, _, title = pattern.parseString(inputstr)
            print(inputstr)
            url, title = pattern.parseString(inputstr)
            return f"* [{title[0]}]({url[0]})\r"

        with open(onetabfilename, 'r', encoding='utf-8') as myfile:
            result = [
                markdown(line) for line in myfile.readlines() if len(line) > 2
            ]

        # 输出结果
        with open(resultfilename, 'w', encoding='utf-8') as myfile:
            myfile.write("# url\r\r")
            myfile.writelines(result)
